package br.com.gestantes.controle;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import br.com.gestantes.modelo.autenticacao.Usuario;

@Controller
public class AdminController {
	
	private static final Logger logger = LoggerFactory.getLogger(AdminController.class);
	
	@RequestMapping(value = "/admin/usuarios", method = RequestMethod.GET)
	public String listarUsuarios(Locale locale, Model model) {
		logger.info("Usuario Controller.");
				
		List<Usuario> usuarios = new ArrayList<Usuario>();
		
		Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        
    
        String driver = "org.postgresql.Driver";
        String url = "jdbc:postgresql://localhost:5432/gestantes";
        String user = "root";
        String password = "123";

        try {
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, user, password);
            st = con.createStatement();
            rs = st.executeQuery("SELECT USUA_NM_NOME, USUA_NM_EMAIL, USUA_NM_AUTHORITY FROM USUARIO");

            while(rs.next()) {
            	
            	Usuario usuario = new Usuario();
            	
            	usuario.setNome(rs.getString(1));
            	usuario.setEmail(rs.getString(2));
            	usuario.setCargo(rs.getString(3));
                
                usuarios.add(usuario);
            }

        } catch (SQLException ex) {
            
            ex.printStackTrace();

        } catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
               ex.printStackTrace();
            }
        }
        
	    model.addAttribute("usuarios", usuarios);
		
		return "admin/usuarios";
	}
	
}
